package codegen

import (
	"fmt"
	"gitee.com/hxchjm/goge/codegen/utils"
	"gitee.com/hxchjm/goge/codegen/utils/pathx"
	"github.com/siddontang/go/config"
	"strings"
)

const serviceTemplate = `package service

import (
	"context"
	
	"{{.serviceName}}/api"
	"{{.serviceName}}/internal/dao"

	"go-main/library/log"
)

type Service struct {
	dao dao.Dao
}

// New a service and return.
func New(d dao.Dao) (s *Service, cf func(), err error) {
	s = &Service{
		dao: d,
	}
	cf = s.Close
	return
}

// SayHello grpc demo func.
func (s *Service) SayHello(ctx context.Context, req *api.HelloReq) (reply *api.EmptyRsp, err error) {
	reply = new(api.EmptyRsp)
	log.Infof(ctx, "say hello %s", req)
	return
}

// SayHelloURL dam demo func.
func (s *Service) SayHelloURL(ctx context.Context, req *api.HelloReq) (reply *api.HelloRsp, err error) {
	reply = &api.HelloRsp{
		Content: "hello " + req.Name,
	}
	log.Infof(ctx, "hello url %s", req)
	return
}

// Ping the resource.
func (s *Service) Ping(ctx context.Context, e *api.EmptyReq) (*api.EmptyRsp, error) {
	return &api.EmptyRsp{}, s.dao.Ping(ctx)
}

// Close the resource.
func (s *Service) Close() {
}
`

func genService(dir, rootPkg string, cfg *config.Config, filename string) error {
	//name := strings.ToLower(api.Service.Name)
	//filename, err := format.FileNamingFormat(cfg.NamingFormat, name)
	//if err != nil {
	//	return err
	//}

	/*	filename := name
		configName := filename
		if strings.HasSuffix(filename, "-api") {
			filename = strings.ReplaceAll(filename, "-api", "")
		}*/

	return utils.GenFile(utils.FileGenConfig{
		Dir:          dir,
		Subdir:       serviceDir,
		Filename:     filename,
		TemplateName: "mainTemplate",
		//Category:        category,
		//TemplateFile:    mainTemplateFile,
		BuiltinTemplate: serviceTemplate,
		Data: map[string]string{
			"importPackages": genServiceImports(rootPkg),
			"serviceName":    rootPkg,
		},
	})
}

func genServiceImports(parentPkg string) string {
	var imports []string
	imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, appDir)))
	//imports = append(imports, fmt.Sprintf("\"%s/core/conf\"", vars.ProjectOpenSourceURL))
	//imports = append(imports, fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL))
	return strings.Join(imports, "\n\t")
}
